# -*- coding: utf-8 -*-
from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.http import Request
from imax.items import ImaxItem

class ImaxSPider(Spider):
	name = "imax"
	allowed_domains = ["imax.im"]
	start_urls = ["http://imax.im/movies"]

	total_page = 806
	root_url = "http://imax.im"

	def parse(self, response):
		reqs = []
		# for page_num in range(2,self.__class__.total_page):
		for page_num in range(1,2):
			page_url = "http://imax.im/movies/" + "?page=" + str(page_num)
			req = Request(page_url, callback=self.parse_page)
			reqs.append(req)
		return reqs



	def parse_page(self, response):
		sel = Selector(response)
		movies  = sel.xpath('//*[@id="movies"]/div[2]/section')
		reqs = []

		for movie in movies:
			href = movie.xpath('div/a/@href').extract()
			movie_url = self.__class__.root_url + href[0]
			req = Request(movie_url, callback=self.parse_movie)
			reqs.append(req)

		return reqs


	def parse_movie(self, response):
		sel = Selector(response)
		title = sel.xpath('//*[@id="movie"]/div[1]/div[3]/h1/span[1]/text()').extract()[0]
		year =  sel.xpath('//*[@id="movie"]/div[1]/div[3]/h1/span[2]/text()').extract()[0]

		# print title, year
		item = ImaxItem()
		item['title'] = title
		item['year'] = year
		item['about'] = sel.xpath('//*[@id="movie"]/div[2]/div/span/text()').extract()[0]
		print item['about']
		return item
